package com.android.example.record.utils;

import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Request.Builder;
import okhttp3.RequestBody;

public class OkHttpUtils {

    private static OkHttpClient client;

    /**
     * 创建一个OkHttpClient的对象的单例
     */
    private synchronized static OkHttpClient getOkHttpClientInstance() {
        if (client == null) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder()
                    // 设置连接超时等属性，不设置可能会报异常
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(120, TimeUnit.SECONDS)
                    .writeTimeout(120, TimeUnit.SECONDS);

            client = builder.build();
        }
        return client;
    }

    /**
     * 获得Request实例(不带进度)，上传数据
     *
     * @param url 上传的服务器地址
     * @return Request
     */
    private static Request getRequest(String url, String json) {
        MediaType contentType = MediaType.parse("application/json; charset=utf-8");
        RequestBody requestBody = RequestBody.create(json, contentType);
        Request.Builder builder = new Request.Builder();
        builder.url(url).post(requestBody);
        return builder.build();
    }

    /**
     * 获得Request实例(不带进度)，用于测试是否能连接上服务器
     *
     * @param url 服务器地址
     * @return Request
     */
    private static Request getRequest(String url) {
        return new Builder().url(url).get().build();
    }

    /**
     * 根据url，发送异步Post请求(不带进度)
     *
     * @param url      提交到服务器的地址
     * @param json     接口格式
     * @param callback OkHttp的回调接口
     */
    public static void doPostRequest(String url, String json, Callback callback) {
        Call call = getOkHttpClientInstance().newCall(getRequest(url, json));
        call.enqueue(callback);
    }

    /**
     * 根据url，发送异步Get请求
     *
     * @param url      提交到服务器的地址
     * @param callback OkHttp的回调接口
     */
    public static void doGetRequest(String url, Callback callback) {
        Call call = getOkHttpClientInstance().newCall(getRequest(url));
        call.enqueue(callback);
    }
}
